//
//  AppDelegate+OAuthResponse.m
//  TestJSPay
//
//  Created by hongliang on 16/3/14.
//  Copyright © 2016年 hongliang. All rights reserved.
//

#import "AppDelegate+OAuthResponse.h"
#import "WXPayData.h"

extern NSString* const WeChat_AppID;
NSString* const didWeChatPayFinishedNotification = @"didWeChatPayFinishedNotification";

@implementation AppDelegate (OAuthResponse)

-(void) onReq:(BaseReq*)req {
    NSLog(@"open id is %@", req.openID);
}

-(void) onResp:(BaseResp*)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        //微信登录返回处理
    }else if([resp isKindOfClass:[SendMessageToWXResp class]]){
        //微信分享返回处理
        if (WXErrCodeUserCancel == resp.errCode){
            return;
        }
        //NSLog(@"resp.errCode = %d", resp.errCode);
    }else if ([resp isKindOfClass:[PayResp class]]){
        //微信支付返回处理
        NSError* error = nil;
        BOOL isSuccess = [WXPayData parseWeChatPayPayResp:(PayResp*)resp error:&error];
        if (isSuccess) {
            //支付成功
            [[NSNotificationCenter defaultCenter] postNotificationName:didWeChatPayFinishedNotification object:nil userInfo:nil];
        }else {
            //支付失败
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:didWeChatPayFinishedNotification object:nil userInfo:@{@"error":error}];
            });
        }
    }
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    if ([url.absoluteString hasPrefix:WeChat_AppID]) {
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WXApi handleOpenURL:url delegate:self];
}
@end
